<template>
  <div>
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">
      <el-form-item label="拼购名称：" prop="group_purchase_name">
        <el-input
          :disabled="disabled"
          class="w300"
          placeholder="请输入"
          v-model="form.group_purchase_name"
        ></el-input>
      </el-form-item>
      <el-form-item label="拼购商品：" prop="ad_title">
        <div class="bflex">
          <div>
            <img class="showimg" v-if="form.commodity_imgurl" :src="imgUrl + form.commodity_imgurl" alt="" />
            <el-button @click="lookpro" type="text" class="mr16">{{ form.commodity_name }}</el-button>
          </div>
          <el-button type="text" @click="handleCommand" v-if="!disabled">
            {{
            form.commodity_id ? "修改" : '添加'
            }}
          </el-button>
        </div>
      </el-form-item>
      <el-form-item label="显示价格：" prop="group_purchase_price">
        <el-input
          class="w300"
          :disabled="disabled"
          type="number"
          placeholder="请输入"
          v-model="form.group_purchase_price"
        ></el-input>
        元
      </el-form-item>
      <el-form-item label="价格/库存：">
        <el-button size="mini" type="primary" @click="openRep">{{disabled ? "查 看" : "设 置"}}</el-button>
      </el-form-item>
      <el-form-item label="上架状态：" prop="group_release">
        <el-radio-group v-model="form.group_release" :disabled="disabled">
          <el-radio v-for="(item, key) in lineStatus" :key="key" :label="key">{{
            item
          }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="拼购时间：" prop="datetimerange">
        <el-date-picker
          :disabled="disabled"
          v-model="form.datetimerange"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item label="成团人数：" prop="user_count">
        <el-input
          :disabled="disabled"
          class="w300"
          type="number"
          placeholder="请输入"
          v-model="form.user_count"
        ></el-input>
        人
      </el-form-item>
      <el-form-item label="成团时间：" prop="group_time">
        <el-input
          :disabled="disabled"
          class="w100"
          type="number"
          placeholder="请输入"
          v-model="form.group_time"
        ></el-input>
        <span> 小时</span>
        <p class="tip">限定时间未能成团则拼团失败</p>
      </el-form-item>
      <el-form-item label-width="120px">
        <el-button @click="goback">返 回</el-button>
        <el-button v-if="!disabled" type="primary" @click="saveData">保 存</el-button>
      </el-form-item>
    </el-form>

    <!-- // 设置链接 -->
    <el-dialog title="设置链接" width="800px" :visible.sync="dialogVisible">
      <div>
        <div>
          <el-form size="small" :inline="true" :model="queryObj">
            <el-form-item label="系列">
              <el-select v-model="queryObj.series_id" placeholder="全部">
                <el-option
                  v-for="item in seriesList"
                  :key="item.series_id"
                  :label="item.series_name"
                  :value="item.series_id"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="关键字">
              <el-input
                placeholder="请输入"
                clearable
                prefix-icon="el-icon-search"
                v-model="queryObj.query_value"
              >
              </el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                @click="_getCommodityListReset"
                >查询</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <div>
          <el-table
            :data="mainList"
            stripe
            class="small-table"
            style="width: 100%"
          >
            <el-table-column prop="info_id" label="产品ID" width="100">
            </el-table-column>
            <el-table-column prop="info_code" label="产品编号">
            </el-table-column>
            <el-table-column prop="info_content" label="线路名称">
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template slot-scope="scope">
                <el-button type="text" @click="setUrlLink(scope.row)"
                  >添加</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="pagecon"
            background
            layout="prev, pager, next"
            :current-page.sync="page.page"
            @current-change="_getCommodityList"
            :total="page.total"
          >
          </el-pagination>
        </div>
      </div>
    </el-dialog>

    <!-- // 遮罩框 -->
    <div v-show="hasSet" class="upmask">
      <div class="close" @click="closeMask">
        <i class="iconfont icon-delete"></i>
      </div>
      <div>
        <commodRepertory ref="commodRepertory" :type="disabled ? 'look' : ''" :nocost="true" />
      </div>
    </div>
  </div>
</template>

<script>
import { getSeriesAll } from "api/lineManagement/seriesMgAPI";
import { getCommodityList } from "api/lineManagement/lineCommodity";
import commodRepertory from "@/views/lineManagement/components/commodRepertory";
import {
  addOrModifyGroupPurchase,
  getGroupPurchaseDetail
} from 'api/marketingManagement/groupBuying';
import config from "api/config";
export default {
  components: {
    commodRepertory
  },
  computed: {
    disabled() {
      return this.type == 'look'
    }
  },
  data() {
    return {
      dialogVisible: false,
      hasSet: false,
      imgUrl: config.imgUrl,
      form: {
        commodity_name: "",
        commodity_id: "",
        commodity_imgurl: "",
        datetimerange: []
      },
      rules: {},
      seriesList: [],
      lineStatus: {
        2: "上架",
        9: "下架"
      },
      queryObj: {},
      page: {
        page: 1,
        limit: 10,
        total: 0
      },
      mainList: []
    };
  },
  methods: {
    openRep() {
      this.hasSet = true;
    },
    closeMask() {
      this.hasSet = false;
    },
    handleCommand() {
      this.dialogVisible = true;
      if (!this.mainList.length) {
        this._getCommodityList();
      }
    },
    goback() {
      this.$router.back();
    },
    setUrlLink(row) {
      this.form.commodity_name = row.info_content;
      this.form.commodity_id = row.info_id;
      this.form.commodity_imgurl = row.info_imgurl;
      this.dialogVisible = false;
    },
    changeFen(obj, type) {
      let changeFn;
      if (type == "magnify") {
        changeFn = val => val * 100;
      } else if (type == "shrink") {
        changeFn = val => val / 100;
      }
      obj.group_purchase_price = changeFn(obj.group_purchase_price);
      obj.repertoryArr.forEach(item => {
        item.month_detail.forEach(subitem => {
          subitem.price = changeFn(subitem.price);
          subitem.child_price = changeFn(subitem.child_price);
          subitem.diff_price = changeFn(subitem.diff_price);
        });
      });
    },
    // 获取详情
    async _getGroupPurchaseDetail() {
      let res = await getGroupPurchaseDetail(this.curid)
      let data = res.rData[0]
      this.changeFen(data, 'shrink')
      this.$refs.commodRepertory.setData(data)
      delete data.repertoryArr
      data.datetimerange = [new Date(data.start_time*1000), new Date(data.end_time*1000)]
      this.form = data
    },
    async saveData() {
      let sendData = { ...this.form };
      let reData = await this.$refs.commodRepertory.getData();
      sendData = { ...sendData, ...reData };
      if (sendData.datetimerange.length) {
        sendData.start_time = (+sendData.datetimerange[0] / 1000) | 0;
        sendData.end_time = (+sendData.datetimerange[1] / 1000) | 0;
      }
      // 转换价格
      this.changeFen(sendData, 'magnify')
      await addOrModifyGroupPurchase(sendData)
      // 添加成功
      this.$message({
        message: "添加成功",
        type: "success"
      });
      this.$router.push("/home/groupBuyingList");
      // console.log(sendData);
    },
    lookpro() {
      this.$router.push({
        path: '/home/lineCommodityAdd',
        query: { id: this.form.commodity_id, type: 'look' }
      });
    },
    // 获取商品列表
    _getCommodityList() {
      let data = { ...this.queryObj };
      data.pageInfo = { ...this.page };
      getCommodityList(data).then(res => {
        let pageInfo = res.pageInfo;
        this.page.total = pageInfo.Total;
        this.page.page = pageInfo.page;
        this.mainList = res.rData.map(item => ({
          info_id: item.commodity_id,
          info_code: item.commodity_code,
          info_content: item.commodity_name,
          info_imgurl: item.commodity_img.split(",")[0]
        }));
      });
    },
    async _getCommodityListReset() {
      this.page.page = 1;
      this._getCommodityList();
    },
    async _getSeriesAll() {
      let res = await getSeriesAll();
      this.seriesList = res.rData;
    }
  },
  created() {
    this._getSeriesAll();
    this.type = this.$route.query.type;
    if (this.type) {
      // 获取详情
      this.curid = this.$route.query.id;
      this._getGroupPurchaseDetail();
    }
  }
};
</script>

<style lang="scss" scoped>
.showimg{
  width: 200px;
}
.bflex{
  display: flex;
  align-items: flex-end;
}
.upmask {
  position: absolute;
  left: 0;
  width: 100%;
  top: 0;
  background: #fff;
  padding: 16px;
  min-height: 100%;
}
.close {
  padding: 10px;
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 100;
  transition: 0.3 all;
  cursor: pointer;
  &:hover {
    color: red;
  }
}
.w100 {
  width: 100px;
}
.w300 {
  width: 300px;
}
.tip {
  color: #999;
}
</style>
